package com.action;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import com.beans.StudentInfo;
import com.service.StudentService;

@Controller
public class StudentAction {
	
	@Resource
	StudentService studentService;
	
	@GetMapping("error")
	public void gotoError() {
		int x=0/0;
		System.out.println(x);
	}

	//学生列表
	@GetMapping("/students")
	public String students(ModelMap m) {
		m.put("stuList", studentService.findAll());
		return "student/student_list";
	}
	
	//转到添加学生界面
	@GetMapping("/student")
	public String student(ModelMap m) {
		m.put("student", new StudentInfo());
		return "student/student_add";
	}
	
	//添加学生
	@PostMapping("studentAdd")
	public String addStudent(@ModelAttribute ("stu")  @Validated StudentInfo stu,BindingResult result,ModelMap m) {
		if(result.hasErrors()) {	
			m.put("msg", "校验失败");
			List<FieldError> errorList=result.getFieldErrors();
			errorList.forEach(e->System.out.println(e.getField()+":"+e.getDefaultMessage()));				
		}else {			
			stu.setCreateTime(new Date());
			studentService.addStudent(stu);
			m.put("student", stu);
			m.put("msg", "添加成功");
		}
		return "student/student_add";
	}
	
	//删除学生
	@GetMapping("delete/{id}")
	public String deleteStu(@PathVariable("id") Integer id) {
		studentService.deleteStuById(id);
		return "forward:/students";
	}
	
	//转到修改界面
	@GetMapping("/student/edit/{id}")
	public String edit(@PathVariable("id") Integer id,ModelMap m) {
		StudentInfo s=studentService.getStuById(id);
		m.put("student", s);
		return "student/student_edit";
	}
	
	//修改
	@PostMapping("/studentEdit")
	public String edit(StudentInfo stu,ModelMap m) {
		studentService.updateStu(stu);
		m.put("student", stu);
		m.put("msg", "更新成功");
		return "student/student_edit";
	}
	
}
